package com.ruoyi.system.handler;

import com.alibaba.fastjson.JSONObject;
import jakarta.websocket.*;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 群聊 WebSocket 端点
 * 访问路径：ws://ip:port/ws/group-chat/{groupId}/{userId}
 */
@ServerEndpoint("/ws/group-chat/{groupId}/{userId}")
@Component
public class GroupChatController {

    // 存储群组与用户会话的映射（线程安全）
    private static final ConcurrentHashMap<String, Set<Session>> groupSessionMap = new ConcurrentHashMap<>();

    // 会话与用户ID的映射
    private static final ConcurrentHashMap<Session, String> sessionUserIdMap = new ConcurrentHashMap<>();

    /**
     * 连接建立时触发
     */
    @OnOpen
    public void onOpen(Session session,
                      @PathParam("groupId") String groupId,
                      @PathParam("userId") String userId) {
        // 1. 将用户加入群组
        groupSessionMap.computeIfAbsent(groupId, k -> new CopyOnWriteArraySet<>()).add(session);
        // 2. 记录用户会话
        sessionUserIdMap.put(session, userId);

        // 3. 广播"用户加入"消息
        String joinMsg = buildMessage("系统", userId + " 加入群聊");
        broadcast(groupId, joinMsg, session); // 排除自己

        System.out.println("用户 " + userId + " 加入群聊 " + groupId + 
                           "，当前人数：" + groupSessionMap.get(groupId).size());
    }

    /**
     * 收到消息时触发
     */
    @OnMessage
    public void onMessage(String message, Session session,
                         @PathParam("groupId") String groupId,
                         @PathParam("userId") String userId) {
        // 1. 构建标准化消息
        String formattedMsg = buildMessage(userId, message);
        // 2. 广播给群内所有用户
        broadcast(groupId, formattedMsg, null);

        System.out.println("群聊 " + groupId + "，用户 " + userId + "：" + message);
    }

    /**
     * 连接关闭时触发
     */
    @OnClose
    public void onClose(Session session,
                       @PathParam("groupId") String groupId,
                       @PathParam("userId") String userId) {
        // 1. 移除用户会话
        Set<Session> sessions = groupSessionMap.get(groupId);
        if (sessions != null) {
            sessions.remove(session);
            // 若群为空，删除群组
            if (sessions.isEmpty()) {
                groupSessionMap.remove(groupId);
            }
        }
        sessionUserIdMap.remove(session);

        // 2. 广播"用户离开"消息
        String leaveMsg = buildMessage("系统", userId + " 离开群聊");
        broadcast(groupId, leaveMsg, session);

        System.out.println("用户 " + userId + " 离开群聊 " + groupId);
    }

    /**
     * 发生错误时触发
     */
    @OnError
    public void onError(Session session, Throwable error) {
        String userId = sessionUserIdMap.get(session);
        System.err.println("用户 " + userId + " 连接错误：" + error);
    }

    /**
     * 广播消息到群组（可排除特定用户）
     */
    private void broadcast(String groupId, String message, Session excludeSession) {
        Set<Session> sessions = groupSessionMap.get(groupId);
        if (sessions == null || sessions.isEmpty()) return;

        for (Session session : sessions) {
            if (session != excludeSession && session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message); // 发送消息
                } catch (IOException e) {
                    System.err.println("消息发送失败：" + e.getMessage());
                }
            }
        }
    }

    /**
     * 构建标准化消息（JSON格式）
     */
    private String buildMessage(String sender, String content) {

        return content;
    }
}